<template>
  <div class="mesProductProcessSteps" v-loading="loading">
    <el-container>
      <el-aside width="260px">
        <el-input
          :placeholder="$t('common.filter')"
          v-model="filterText"
          clearable
        ></el-input>
        <div class="treeBtns">
          <el-button
            @click="handleNodeAdd('add', $t('common.add'))"
            type="primary"
          >
            {{ $t("common.add") }}
          </el-button>
          <el-button
            @click="handleNodeAdd('copy', $t('mesProductProcessSteps.copy'))"
            type="primary"
          >
            {{ $t("mesProductProcessSteps.copy") }}
          </el-button>
          <el-button @click="handleNodeDelete" type="danger">
            {{ $t("common.delete") }}
          </el-button>
        </div>
        <el-scrollbar class="scrollbarTree">
          <el-tree
            :props="nodeProp"
            lazy
            :load="loadNode"
            :data="data"
            :indent="8"
            :default-expand-all="false"
            ref="tree"
            highlight-current
            check-on-click-node
            :default-expanded-keys="expandedNodes"
            @node-expand="handleNodeExpand"
            @node-collapse="handleNodeCollapse" 
            node-key="id"
            :current-node-key="currentKey"
            @node-click="handleNodeClick"
            :filter-node-method="filterNode"
          >
            <template v-slot:default="{ node, data }">
              <div class="flex label-pack">
                <span class="padd-r-5" style="width: 20px;">
                  <img v-if="data.child" src="@/assets/images/xia.png" />
                  <img v-else src="@/assets/images/ping.png" />
                </span>
                <svgIcon
                  :color="node.isCurrent ? '#3d82ea' : '#b6c0c9'"
                  :type="geticonType(data)"
                />
                <span class="padd-l-5">{{ data.label }}</span>
              </div>
            </template>
          </el-tree>
        </el-scrollbar>
      </el-aside>
      <el-main class="main-pack">
        <TableSteps ref="tableSteps" @refreshTree="refreshTree"></TableSteps>
      </el-main>
    </el-container>
    <ele-form-drawer
      class="dialog-pack"
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog"
      :request-fn="handleSubmit"
      :visible.sync="visible"
      :title="title"
    >
      <template v-slot:seriesName="{ formData }">
        <el-input
          v-model="formData.series"
          readonly
          :placeholder="$t('mesProductProcessSteps.placeholderSeries')"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="seriesVisible = true"
          ></el-button>
        </el-input>
      </template>
      <template v-slot:prodName="{ formData }">
        <el-input
          v-model="formData.prodName"
          readonly
          :placeholder="$t('mesProductProcessSteps.placeholderModel')"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="$refs.selectProd.init(formDataDialog)"
          ></el-button>
        </el-input>
      </template>
    </ele-form-drawer>
    <!--获取系列表格 -->
    <ele-dialog-table
      :title="$t('mesProductProcessSteps.seriesModelTitle')"
      width="800px"
      :visible.sync="seriesVisible"
      :formConfig="seriesSearchDialog"
      :column="seriesColumn"
      @getSelectData="getSelectSeries"
      :getList="selectlist"
      :hasFooter="true"
    ></ele-dialog-table>
    <!--获取型号表格 -->
    <SelectProd ref="selectProd" @getSelectProd="getSelectProd"></SelectProd>
  </div>
</template>

<script>
import svgIcon from "./components/svgIcon.vue";
import {
  getStepSeries,
  selectlist,
  getStepTechnology,
  getStepProcess,
  createNode,
  copyNode,
  deleteNode,
} from "@/api/process/mesProductProcessSteps";
import {
  rowConfig,
  formDescDialogMixins,
  seriesColumn,
  seriesSearchDialog,
} from "./config.js";
import TableSteps from "./components/tableSteps";
import SelectProd from "./components/selectProd";

export default {
  name: "mesProductProcessSteps",
  mixins: [formDescDialogMixins],
  components: { TableSteps, SelectProd, svgIcon },
  props: {},
  data() {
    return {
      expandedNodes: [], // 用于记录展开的节点
      iconType: [
        {
          value: "xl",
          name: $i18n.t("mesProductProcessSteps.series"),
          type: 1,
        },
        { value: "xh", name: $i18n.t("mesProductProcessSteps.model"), type: 2 },
        {
          value: "gy",
          name: $i18n.t("mesProductProcessSteps.technology"),
          type: 3,
        },
        {
          value: "gx",
          name: $i18n.t("mesProductProcessSteps.workCell"),
          type: 4,
        },
      ],
      selectlist,
      seriesVisible: false,
      seriesSearchDialog,
      seriesColumn,
      loading: false,
      title: "",
      titleCode: "",
      visible: false,
      isLoading: false,
      formDataDialog: {},
      nodeProp: {
        isLeaf: (data) => !data.child,
      },
      filterText: "",
      data: [],
      currentData: {}, //当前node数据
      currentKey: null,
      prodLoading: false,
      currentRow: {},
      saveCurrentData: [],
    };
  },
  computed: {
    geticonType() {
      return function (data) {
        const item = this.iconType.find(
          (ite) => data.levelType == ite.value
        ) || { type: 0 };
        return item.type;
      };
    },
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getStepSeries();
  },
  methods: {
    refreshTree() {
      this.getStepSeries();
    },
    //筛选过滤
    filterNode(value, data) {
      if (!value) return true;
      return data["label"].indexOf(value) !== -1;
    },

    refreshNode(key) {
      // 获取当前节点，key可以在@node-click和:load绑定函数的回调参数node用变量存储后有需要刷新的地方取node.key
      let node = this.$refs.tree.getNode(key);
      //  设置未进行懒加载状态
      node.loaded = false;
      // 重新展开节点就会间接重新触发load达到刷新效果
      node.expand();
    },

    loadNode(node, resolve) {
      if (node.level == 0) return;

      if (["xl", "xh"].includes(node.data.levelType)) {
        const params = {
          seriesCode: node.data.seriesCode,
          prodCode: node.data.prodCode,
        };
        this.getStepTechnology(params, resolve);
      } else if (node.data.levelType == "gy") {
        const {
          seriesCode,
          technologyCode,
          prodCode,
          versionNumber,
        } = node.data;
        const params = {
          seriesCode,
          technologyCode,
          prodCode,
          versionNumber,
        };
        this.getStepProcess(params, resolve);
      } else {
        resolve([]);
      }
    },

    // 树节点展开
    handleNodeExpand(data) {
      // 保存当前展开的节点
      let flag = false
      this.expandedNodes.some(item => {
        if (item === data.id) { // 判断当前节点是否存在， 存在不做处理
          flag = true
          return true
        }
      })
      if (!flag) { // 不存在则存到数组里
        this.expandedNodes.push(data.id)
      }
    },
    // 树节点关闭
    handleNodeCollapse(data) {
      // 删除当前关闭的节点
      this.expandedNodes.some((item, i) => {
        if (item === data.id) {
          this.expandedNodes.splice(i, 1)
        }
      })
      this.removeChildrenIds(data) // 这里主要针对多级树状结构，当关闭父节点时，递归删除父节点下的所有子节点
    },
    // 删除树子节点
    removeChildrenIds(data) {
      const ts = this
      if (data.children) {
        data.children.forEach(function(item) {
          const index = ts.expandedNodes.indexOf(item.id)
          if (index > 0) {
            ts.expandedNodes.splice(index, 1)
          }
          ts.removeChildrenIds(item)
        })
      }
    },
    //获取组织树
    getStepSeries() {
      this.loading = true;
      getStepSeries()
        .then((res) => {
          let data = res.data.result || [];
          data.forEach((item) => {
            item.label = `${item.seriesName || ""}(${item.seriesCode || "-"})`;
            item.code = item.seriesCode;
          });
          this.data = data;
          this.$nextTick(() => {
          this.filterText = ""
           this.$refs.tree.setCheckedKeys(this.expandedNodes);
            this.expandedNodes.map((ite) => { 
              this.refreshNode(ite);
            });
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 产品工艺步骤-分级加载-获取产品/工艺
    getStepTechnology(params = {}, resolve) {
      getStepTechnology(params).then((res) => {
        let data = res.data.result || [];
        data.forEach((item) => {
          //工艺
          if (item.levelType == "gy") {
            item.label = `${item.technologyName}(${item.versionNumber})`;
            item.code = item.technologyCode;
          }
          //型号
          if (item.levelType == "xh") {
            item.label = item.prodName;
            item.code = item.prodCode;
          }
        });
        resolve(data);
      });
    },
    //获取树状工序
    getStepProcess(params = {}, resolve) {
      getStepProcess(params).then((res) => {
        let data = res.data.result || [];
        data.forEach((item) => {
          item.label = item.processName;
          item.code = item.processCode;
        });
        resolve(data);
      });
    },
    //节点添加、复制
    handleNodeAdd(code, title) {
      this.title = title;
      this.titleCode = code;
      if (code == "copy" && this.currentData.levelType != "gx") {
        this.$message.error($i18n.t("mesProductProcessSteps.processError"));
        return;
      }

      this.visible = true;
    },
    //节点删除
    handleNodeDelete() {
      if (Object.keys(this.currentData).length == 0) {
        this.$message.error($i18n.t("mesProductProcessSteps.nodeDeleteTip"));
        return;
      }
      this.$confirm(
        $i18n.t("mesProductProcessSteps.nodeDeleteNote"),
        $i18n.t("common.tip"),
        {
          confirmButtonText: $i18n.t("common.ok"),
          cancelButtonText: $i18n.t("common.cancel"),
          type: "warning",
        }
      ).then(() => {
        this.deleteNode();
      });
    },
    deleteNode() {
      const data =
        this.currentData.levelType == "xl"
          ? { seriesCode: this.currentData.seriesCode }
          : this.currentData;
      this.loading = true;
      deleteNode(data)
        .then((res) => {
          this.$message.success($i18n.t("common.deleteSuccess"));
          this.getStepSeries();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //节点选择事件
    handleNodeClick(data, node, self) {
      // console.log(data, node, self);
      this.currentData = data;
      this.saveCurrentData.push(data.id);
      this.$nextTick(() => {
        this.$refs.tableSteps.init(this.currentData, this.saveCurrentData);
      });
      //   ;
    },
    //获取产品表格
    getProductTable() {
      this.prodLoading = true;
      const { id } = this.currentData;
      getProductTable(id)
        .then((res) => {
          this.$refs.prodTable.data = res.data.result || [];
        })
        .finally(() => {
          this.prodLoading = false;
        });
    },
    //选择系列
    getSelectSeries(data) {
      console.log(data);
      if (data.length != 1) {
        // $i18n.t("mesProductProcessSteps.seriesErrorTip"),
        this.$message.error($i18n.t("mesProductProcessSteps.seriesErrorTip"));
        return;
      }
      const { defaultFlag, seriesCode, seriesName } = data[0];
      this.formDataDialog = {
        isDefaultSeries: defaultFlag,
        seriesCode,
        seriesName,
        series: `${seriesName}(${seriesCode})`,
      };
    },
    //选择型号
    getSelectProd(data) {
      const { goodsName, goodsCode } = data[0];
      const {
        isDefaultSeries,
        seriesCode,
        seriesName,
        series,
      } = this.formDataDialog;
      this.formDataDialog = {
        prodName: goodsName,
        prodCode: goodsCode,
        isDefaultSeries,
        seriesCode,
        seriesName,
        series,
      };
    },

    //新增，复制节点
    handleSubmit(data) {
      const {
        isDefaultSeries,
        seriesCode,
        seriesName,
        processCode = "",
        prodCode,
        prodName,
        technology = "",
      } = data;
      const [name, code] = processCode.split("@");
      const [
        technologyName,
        technologyCode,
        versionNumber,
        id,
      ] = technology.split("@");
      let params = {
        seriesCode,
        seriesName,
        isDefaultSeries,
        prodCode,
        prodName,
        technologyId: id,
        technologyCode,
        technologyName,
        versionNumber,
        processCode: code,
        processName: name,
      };

      let obj = {};
      if (this.titleCode == "add") {
        obj = {
          data: params,
          api: createNode,
          message: $i18n.t("common.addSuccess"),
        };
      } else {
        obj = {
          data: {
            ...params,
            originalSeriesCode: this.currentData.seriesCode,
            originalProdCode: this.currentData.prodCode,
            originalTechnologyCode: this.currentData.technologyCode,
            originalVersionNumber: this.currentData.versionNumber,
            originalProcessCode: this.currentData.processCode,
          },
          api: copyNode,
          message: $i18n.t("common.copyMsg"),
        };
      }
      this.doSubmit(obj);
    },
    doSubmit({ data, api, message }) {
      this.isLoading = true;
      api(data)
        .then((res) => {
          this.$message.success(message);
          this.getStepSeries();
          this.visible = false;
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.mesProductProcessSteps {
  background-color: #eff2fb;
  padding: 0;
  margin: -10px;
  min-height: calc(100vh - 112px);
  .el-main {
    padding: 10px;
    padding-top: 0;
  }

  .el-aside {
    background-color: #ffffff;
    padding: 10px;
    min-height: calc(100vh - 112px);
  }
  .scrollbarTree {
    height: calc(100vh - 170px - 52px);
    box-sizing: border-box;
    background-color: #ffffff;
    /deep/ .el-tree-node > .el-tree-node__children {
      overflow: inherit;
    }
  }
  .treeBtns {
    margin: 10px 0;
    display: flex;
    justify-content: space-between;
  }
  .main-pack {
    //width: calc(100vw - 365px);
    margin-left: 10px;
    background-color: white;
    padding: 10px;
    padding-bottom: 0;
  }
  .flex {
    display: flex;
  }

  .label-pack {
    span {
      display: block;
    }

    .padd-l-5 {
      padding-left: 5px;
      font-size: 13px;
    }
    .padd-r-5 {
      padding-right: 5px;
    }
  }
}
</style>
